package com.hsnn.medstgmini.base.std.controller;
/**
 * StdExpertController. 专家库controller 控制类
 */


import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.base.dict.controller.DicPharController;
import com.hsnn.medstgmini.base.dict.dao.impl.DicAreaDaoImpl;
import com.hsnn.medstgmini.base.dict.model.DicArea;
import com.hsnn.medstgmini.base.dict.model.DicExperttype;
import com.hsnn.medstgmini.base.std.model.StdExpert;
import com.hsnn.medstgmini.base.std.model.StdExpertLog;
import com.hsnn.medstgmini.base.std.service.StdExpertManager;
import com.hsnn.medstgmini.exception.MSException;
import com.hsnn.medstgmini.pro.project.service.BidExpertExtractRuleManager;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.util.AccountUtil;
import com.hsnn.medstgmini.util.DateUtil;
import com.hsnn.medstgmini.util.ExcelUtil;
import com.hsnn.medstgmini.util.Pagination;


@Controller
@RequestMapping("/stdExpert")
public class StdExpertController {
	
	private static final Logger log = Logger.getLogger(DicPharController.class);
	
	@Autowired
	private StdExpertManager stdExpertManager;
	
	@Autowired
	private HttpServletRequest request;
	
	@Autowired
	private DicAreaDaoImpl dicAreaDaoImpl;
	@Autowired
	private BidExpertExtractRuleManager bidExpertExtractManager;
	
	@Autowired
	private HttpSession session;
	
	/**
	 * 获取当前登录人信息
	 * @return
	 */
	public SysUser getUser() {
		return (SysUser) session.getAttribute(Constants.USERINFO);
	}
	
	/**
	 * 专家库列表页面
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping("/expertList")
	public String  expertList()  {
		log.info("enter expertList method");
		return "/base/std/stdExpertList";
	}
	
	
	/**
	 * 
	 *@category 查询专家库列表
	 *@author yanke
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("/getExpertList")
	@ResponseBody
	public Pagination getExpertList(StdExpert stdExpert) {
		log.info("enter getExpertList method");
		printParams();
		Pagination page = new Pagination(request);
		try {
			page.getConditions().put("expSkillsType1", request.getParameter("expSkillsType1"));
			page.getConditions().put("expSkillsType2", request.getParameter("expSkillsType2"));
			page.getConditions().put("expSkillsType3", request.getParameter("expSkillsType3"));
			page.getConditions().put("name", request.getParameter("name"));
			page.getConditions().put("companyId", request.getParameter("companyId"));
			page.getConditions().put("status", request.getParameter("status"));
			stdExpertManager.getStdExpertList(page);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	
	/**
	 * 
	 *@category 跳转新增和编辑页面
	 *@author yanke
	 *@date 2015年6月9日
	 *String
	 */
	@RequestMapping(value={"/add","/edit"})
	public String editExpert(Model model, int opType, String expertId) {
		printParams();
		StdExpert stdExpert = new StdExpert();
		if (opType == Constants.OP_TYPE_EDIT) {
			if (expertId != null && !"".equals(expertId)) {
				stdExpert = stdExpertManager.getStdExpertById(expertId);
				if(stdExpert!=null){
					String areaId = stdExpert.getAreaId();
					if(areaId!=null){
						if("0000".equals(areaId.substring(2, 6))){
							DicArea area = dicAreaDaoImpl.getDicAreaById(areaId);
							model.addAttribute("areaId1",area.getAreaid());
							model.addAttribute("areaName1",area.getAreaname());
						}else if("00".equals(areaId.substring(4, 6))){
							DicArea area2 = dicAreaDaoImpl.getDicAreaById(areaId);
							StringBuffer sb = new StringBuffer(areaId.substring(0, 2));
							DicArea area1 = dicAreaDaoImpl.getDicAreaById(sb.append("0000").toString());
							model.addAttribute("areaId2",area2.getAreaid());
							model.addAttribute("areaName2",area2.getAreaname());
							model.addAttribute("areaId1",area1.getAreaid());
							model.addAttribute("areaName1",area1.getAreaname());
						}else{
							DicArea area3 = dicAreaDaoImpl.getDicAreaById(areaId);
							StringBuffer sb1 = new StringBuffer(areaId.substring(0, 4));
							DicArea area2 = dicAreaDaoImpl.getDicAreaById(sb1.append("00").toString());
							StringBuffer sb2 = new StringBuffer(areaId.substring(0, 2));
							DicArea area1 = dicAreaDaoImpl.getDicAreaById(sb2.append("0000").toString());
							model.addAttribute("areaId3",area3.getAreaid());
							model.addAttribute("areaName3",area3.getAreaname());
							model.addAttribute("areaId2",area2.getAreaid());
							model.addAttribute("areaName2",area2.getAreaname());
							model.addAttribute("areaId1",area1.getAreaid());
							model.addAttribute("areaName1",area1.getAreaname());
						}
					}
					DicExperttype de=null;
					if(StringUtils.isNotBlank(stdExpert.getExpSkills())){
						 de = bidExpertExtractManager.getDicExperttypeById(stdExpert.getExpSkills());	
					}
					
					String expSkillsId1="";
					String expSkillsId2="";
					String expSkillsId3="";
					if(de!=null){
						String deCode = de.getExpertTypeCode();
						if(3==deCode.length()){
							expSkillsId1 = de.getDicExperttypeId();
						}else if(5==deCode.length()){
							DicExperttype deFather = bidExpertExtractManager.getDicExperttypeById(de.getFatherExperttypeId());
							expSkillsId1 = deFather.getDicExperttypeId();
							expSkillsId2 = de.getDicExperttypeId();
						}else if(7==deCode.length()){
							DicExperttype deFather = bidExpertExtractManager.getDicExperttypeById(de.getFatherExperttypeId());
							DicExperttype deTopFather = bidExpertExtractManager.getDicExperttypeById(deFather.getFatherExperttypeId());
							expSkillsId1 = deTopFather.getDicExperttypeId();
							expSkillsId2 = deFather.getDicExperttypeId();
							expSkillsId3 = de.getDicExperttypeId();
						}
					}
					model.addAttribute("expSkillsId1",expSkillsId1);
					model.addAttribute("expSkillsId2",expSkillsId2);
					model.addAttribute("expSkillsId3",expSkillsId3);
					
				}
				stdExpert = stdExpert == null ? new StdExpert() : stdExpert;
			}
		}

		model.addAttribute("opType", opType);
		model.addAttribute("stdExpert", stdExpert);
		return "/base/std/stdExpertEdit";
	}
	
	/**
	 * 
	 *@category 保存专家库信息
	 *@author yanke
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("saveExpert")
	@ResponseBody
	public Pagination saveExpert(StdExpert stdExpert, int opType) {
		printParams();
		Pagination page = new Pagination();
		String area1 = request.getParameter("area1");
		String area2 = request.getParameter("area2");
		String area3 = request.getParameter("area3");
		
		if (stdExpert != null) {
			String inNum = stdExpert.getIdNum();
			char[] charArray = inNum.toCharArray();  
	        for (int i = 0; i < charArray.length; i++) {  
	            if ((charArray[i] >= 0x4e00) && (charArray[i] <= 0x9fbb)) {  
	            	page.setMsg("身份证不能有中文！");
	            	return page;
	            }
	        } 
			try {
					if(area3!=null&&!"".equals(area3)){
						stdExpert.setAreaId(area3);
					}else if(area2!=null&&!"".equals(area2)){
						stdExpert.setAreaId(area2);
					}else{
						stdExpert.setAreaId(area1);
					}
					if(stdExpert.getStatus()==null){
						stdExpert.setStatus(1);
					}
					
					
					stdExpert.setUpdDatetime(new Date());
					SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
					stdExpert.setUpdUser(user.getId());
					stdExpertManager.saveStdExpert(stdExpert);
					page.setSuccess(true);
				
			} catch (MSException e) {
				log.error("",e);
				page.setSuccess(false);
				page.setMsg(e.getMsg());
			} catch (Exception e) {
				log.error("",e);
				page.setSuccess(false);
				page.setMsg("保存失败！");
			}
		}
		return page;
	}
	
	

	
	/**
	 * 
	 *@category 专家库详情
	 *@author yanke
	 *@date 2015年6月9日
	 *String
	 */
	@RequestMapping("stdExpertDetail")
	public String stdExpertDetail(Model model, String expertId) {
		printParams();
		StdExpert stdExpert = new StdExpert();
		String ruleId = request.getParameter("ruleId");
		if(StringUtils.isNotBlank(ruleId)){
			model.addAttribute("ruleId", ruleId);
		}
		if (StringUtils.isNotBlank(expertId)) {
			stdExpert = stdExpertManager.getStdExpertById(expertId);
			stdExpert = stdExpert == null ? new StdExpert() : stdExpert;
		}
		model.addAttribute("stdExpert", stdExpert);
		return "/base/std/stdExpertDetail";
	}
	
	
	
	/**
	 * 
	 *@category 专家库维护记录页面
	 *@author yanke
	 *@date 2015年6月9日
	 *String
	 */
	@RequestMapping("exPertLogList")
	public String exPertLogList(Model model, String expertId) {
		log.info("enter exPertLogList method");
		printParams();
		model.addAttribute("expertId", expertId);
		request.setAttribute("expertCode", request.getParameter("expertCode"));
		try {
			String name = new String(request.getParameter("name").getBytes("iso8859-1"),"utf-8");
			request.setAttribute("name", name);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "/base/std/stdExpertLogList";
	}

	
	/**
	 * 
	 *@category 查看专家库维护记录列表
	 *@author yanke
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("getExpertLogList")
	@ResponseBody
	public Pagination getExpertLogList(StdExpertLog stdExpertLog) {
		log.info("enter getExpertLogList method");
		printParams();
		Pagination page = new Pagination(request);
		if (null != request.getParameter("endTime") && !"".equals(request.getParameter("endTime"))){
			page.getConditions().put("endTime", request.getParameter("endTime"));
		}
		if (null != request.getParameter("startTime") && !"".equals(request.getParameter("startTime"))){
			page.getConditions().put("startTime", request.getParameter("startTime"));
		}
		try {
			List<Object> list = stdExpertManager.getStdExpertLogList(page, stdExpertLog);
			page.setRows(list);
			page.setSuccess(true);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}

	/**
	 * 
	 *@category 跳转到专家库维护记录详情
	 *@author yanke
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("/toStdExpertLogDetail")
	public String  toStdExpertLogDetail() {
		log.info("enter toStdExpertLogDetail method!");
		printParams();
		Pagination  page = new Pagination();
		page.getConditions().put("logId", request.getParameter("logId"));
		List<Map<String,Object>> list = stdExpertManager.getStdExpertLogDetail(page);
		
		// --------begin
				List<Map<String,Object>> dataList = new ArrayList<Map<String,Object>>();
				List<Map<String,Object>> mapList = new ArrayList<Map<String,Object>>();
				String[] cColunm = {"专家编号","专家姓名","性别","专家类别","身份证号码","政治面貌","出生日期","最高学历","最高学位","职称","职称证书号","职务","所属行业","从事专业","从事专业年限","执业资格1","执业资格证书号1","执业资格2","执业资格证书号2","执业资格3","执业资格证书号3","执业资格4","执业资格证书号4","执业资格5","职业资格证书号5","评标专业1","评标专业2","评标专业3","地区","工龄","是否退休","毕业院校","所学专业","工作单位","组织机构代码","单位地址","家庭地址","移动电话","单位电话","住宅电话","邮政编码","电子邮箱","评标经验","备注","状态"};
				String[] eColunm = {"expert_code","name","sex","exp_skills","id_num","political_status","birthDay","edu_bg","edu_degree","tech_pos","tech_pos_cert_no","position","industry","profession","profes_exper","pract_license1","pract_license_cert_no1","pract_license2","pract_license_cert_no2","pract_license3","pract_license_cert_no3","pract_license4","pract_license_cert_no4","pract_license5","pract_license_cert_no5","score_area1","score_area2","score_area3","area_id","service_year","retiredTag","university","major","company_id","org_id","company_addr","home_addr","handphone","comp_phone","telephone","zipcode","email","score_yesrs","remark","status"};
				
				
				for(int i = 0;i<cColunm.length;i++){
					Map<String,Object> map =  new HashMap<String,Object>();
					map.put("colunm", cColunm[i]);//字段名
					Object tempA = list.get(0).get(eColunm[i]);
					Object tempB=null ;
					if(list.size()>1){
						 tempB = list.get(1).get(eColunm[i]);	
					}
					if("专家类别".equals(cColunm[i])){
						DicExperttype deA = bidExpertExtractManager.getDicExperttypeById(tempA.toString());	
						if(list.size()>1){
							DicExperttype deB = bidExpertExtractManager.getDicExperttypeById(tempB.toString());
							tempB = deB!=null?deB.getExpertTypeName():"";
						}
						tempA = deA!=null?deA.getExpertTypeName():"";
					}
					map.put("after", !"status".equals(eColunm[i])?tempA:("1".equals(tempA.toString())?"启用":"停用"));//修改后数据
					map.put("before", list.size()==1?null:(!"status".equals(eColunm[i])?tempB:("1".equals(tempB.toString())?"启用":"停用")));//修改前数据
					
					if(list.size()==1){
						map.put("red", "1");//是否变红加粗 1是 0 否
					}else{
						//判断修改后与修改前数据是否相等
						if(list.get(0).get(eColunm[i])!=null&&list.get(1).get(eColunm[i])!=null&&!list.get(0).get(eColunm[i]).toString().equals(list.get(1).get(eColunm[i]).toString())){
							map.put("red", "1");
						}else{
							map.put("red", "0");
						}
					}
					mapList.add(map);
				}
				for(int i = 0;i<mapList.size();i++){//把要变红的放在list前面
					if("1".equals(mapList.get(i).get("red"))){
						dataList.add(mapList.get(i));
					}
				}
				for(int i = 0;i<mapList.size();i++){
					if("0".equals(mapList.get(i).get("red"))){
						dataList.add(mapList.get(i));
					}
				}
				request.setAttribute("dataList", dataList);
				// --------end
		request.setAttribute("list", list);
		return "/base/std/stdExpertLogDetail";
	}
	
	/**
	 * 
	 *@category 跳转到专家库详情
	 *@author yanke
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("/toStdExpertDetail")
	public String  toStdExpertDetail() {
		printParams();
		log.info("enter toStdExpertDetail method!");
		Pagination  page = new Pagination();
		page.getConditions().put("expertId", request.getParameter("expertId"));
		List<Map<String,Object>> list = stdExpertManager.getStdExpertDetail(page);
		request.setAttribute("list", list);
		return "/base/std/stdExpertDetail";
	}
	
	
	/**
	 * 
	 *@category 启用停用(包含批量)
	 *@author yanke
	 *@date 2015年9月21日
	 *Pagination
	 */
	@RequestMapping(value={"/enable","/disable"})
	@ResponseBody
	public Pagination batchChangeStatus(String array) {
		printParams();
		log.info("enter batchChangeStatus method!");
		Pagination page = new Pagination();
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		try {
			int sum = 0;
			if (array != null && !"".equals(array)) {
				Gson gson = new Gson();
				Type type = new TypeToken<List<StdExpert>>() {}.getType();
				List<StdExpert> list = gson.fromJson(array, type);
				if (list != null && list.size()>0) {
					for (StdExpert se : list) {
						se.setUpdUser(user.getId());
						int count = stdExpertManager.batchChangeStatus(se);
						sum += count;
					}
					page.getConditions().put("sum", sum+"");
					page.setSuccess(true);
				}else{
					page.setSuccess(false);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
		}
		return page;
	}
	
	

	/**
	 * 新增和编辑
	 * @param page
	 */
	@RequestMapping("/stdExpertAddAndEdit")
	@ResponseBody
	public Pagination stdExpertAddAndEdit(StdExpert stdExpert ) {
		printParams();
		Pagination page = new Pagination(request);
		String areaId1 =request.getParameter("area1");
		String areaId2 =request.getParameter("area2");
		String areaId3 =request.getParameter("area3");
		String areaId = null;
		if(StringUtils.isNotBlank(areaId1)){
			areaId = areaId1;
		}
		if(StringUtils.isNotBlank(areaId2)){
			areaId = areaId2;
		}
		if(StringUtils.isNotBlank(areaId3)){
			areaId = areaId3;
		}
		String expSkillsType1 =request.getParameter("expSkillsType1");
		String expSkillsType2 =request.getParameter("expSkillsType2");
		String expSkillsType3 =request.getParameter("expSkillsType3");
		String expSkills = null;
		expSkills=StringUtils.isNotBlank(expSkillsType3)?expSkillsType3:(StringUtils.isNotBlank(expSkillsType2)?expSkillsType2:(StringUtils.isNotBlank(expSkillsType1)?expSkillsType1:null));
		
		SysUser user = (SysUser) request.getSession().getAttribute(Constants.USERINFO);
		try {
			if (stdExpert != null) {
				stdExpert.setAreaId(areaId);
				stdExpert.setExpSkills(expSkills);
				stdExpert.setUpdUser(user.getId());
				
				if(StringUtils.isNotBlank(stdExpert.getExpertId())){//判断是否修改过，没改不让保存
					StdExpert stdExpert2 = stdExpertManager.getStdExpertById(stdExpert.getExpertId());
					Field[] fields = stdExpert.getClass().getDeclaredFields();  
					String[] fieldNames = new String[fields.length];   
					boolean flag = false;
					for (int i=1; i < fields.length-6; i++){  
					    fieldNames[i] = fields[i].getName();
					    String propVaule1 = BeanUtils.getProperty(stdExpert, fieldNames[i]);
					    propVaule1 = propVaule1==null?"":propVaule1;
					    String propVaule2 = BeanUtils.getProperty(stdExpert2, fieldNames[i]);
					    propVaule2 = propVaule2==null?"":propVaule2;
					    if("birthday".equals(fieldNames[i])){
					    	propVaule2 = StringUtils.isNotBlank(propVaule2)?DateUtil.parseDateTime(propVaule2)+"":"";
					    }
					    if(!propVaule1.equals(propVaule2)){
					    	flag = true;
					    	break;
					    }
					}  
					if(!flag){
						page.setMsg("专家信息未做任何修改，不能保存!");
						page.setSuccess(false);
						return page;
					}
				}
				if(StringUtils.isBlank(stdExpert.getExpertCode())){
					stdExpert.setExpertCode(AccountUtil.getStdSequence(Constants.STD_ZHUANJIA_PREFIX, Constants.STD_ZHUANJIA, Constants.STD_ZHUANJIA_LEN));
					page.setMsg(stdExpert.getExpertCode());
				}
				stdExpertManager.addAndEdit(stdExpert, getUser());
				page.setSuccess(true);
			}
		} catch (Exception e) {
			log.error("",e);
			page.setSuccess(false);
		}
		return page;
		
	}


	/**
	 * 
	 *@category 获取参数打印
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@SuppressWarnings("rawtypes")
	public void printParams(){
		Enumeration paramNames = request.getParameterNames();
		try {
			while (paramNames.hasMoreElements()) {
				String paramName = (String) paramNames.nextElement();
				String paramValue = request.getParameter(paramName);
				log.info(paramName+":"+paramValue);
			}
		} catch (Exception e) {
			log.error("",e);
		}
	}
	
	/**
	 * 
	 *@category 导出excel
	 *@author wangbing
	 *@date 2015年6月9日
	 *Pagination
	 */
	@RequestMapping("exportExcel")
	@ResponseBody
	public Pagination exportExcel(HttpServletResponse response,String fileName){
		printParams();
		Pagination page = new Pagination();
		String expSkills = request.getParameter("expSkills");
		String name = request.getParameter("name");
		String companyId = request.getParameter("companyId");
		String status = request.getParameter("status");
		if(StringUtils.isNotBlank(expSkills)){
			page.getConditions().put("expSkills", expSkills.trim());
		}
		if(StringUtils.isNotBlank(name)){
			page.getConditions().put("name", name.trim());
		}
		if(StringUtils.isNotBlank(companyId)){
			page.getConditions().put("companyId", companyId.trim());
		}
		if(StringUtils.isNotBlank(status)){
			page.getConditions().put("status", status.trim());
		}
		
		try {
			response.addHeader("Content-Disposition", "attachment;filename="+new String(fileName.getBytes("GB2312"),"iso8859-1")); 
			OutputStream os= new BufferedOutputStream(response.getOutputStream());  
			 response.setContentType("application/vnd.ms-excel;charset=utf-8");  
			 stdExpertManager.getStdExpertNoPage(page);
			 String title = "专家";
			 String[] headers = {"编号","姓名","性别","专家类别","身份证号码","政治面貌","出生日期","最高学历","最高学位","职称","职称证书号","职务","所属行业","从事专业","从事专业年限","执业资格1","执业资格证书号1","执业资格2","执业资格证书号2","执业资格3","执业资格证书号3","执业资格4","执业资格证书号4","执业资格5","职业资格证书号5","评标专业1","评标专业2","评标专业3","地区","工龄","是否退休","毕业院校","所学专业","工作单位","组织机构代码","单位地址","家庭地址","移动电话","单位电话","住宅电话","邮政编码","电子邮箱","评标经验","备注","状态"};
			 String[] alias = {"expertCode","name","sex","expSkills","idNum","politicalStatus","birthday","eduBg","eduDegree","techPos","techPosCertNo","position","industry","profession","profesExper","practLicense1","practLicenseCertNo1","practLicense2","practLicenseCertNo2","practLicense3","practLicenseCertNo3","practLicense4","practLicenseCertNo4","practLicense5","practLicenseCertNo5","scoreArea1","scoreArea2","scoreArea3","areaId","serviceYear","retired","university","major","companyId","orgId","companyAddr","homeAddr","handphone","compPhone","telephone","zipcode","email","scoreYesrs","remark","status"};
			 ExcelUtil.exportExcel(page, os, title, headers, alias);
		} catch (Exception e) {
			page.setSuccess(false);
			e.printStackTrace();
		}
		return page;
	}
	

}
